﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using QD.Serialization;

namespace QD.Config
{
    /// <summary>
    /// 配置文件抽象基类
    /// </summary>
    public abstract class ConfigsBase
    {
        protected abstract string ConfigFilePath
        {
            get;
        }
        protected abstract System.Type ConfigInfoType
        {
            get;
        }

        protected object lockobj = new object();

        /// <summary>
        /// 从文件中加载配置
        /// </summary>
        /// <returns></returns>
        protected IConfig LoadConfig()
        {
            lock (lockobj)
            {
                if (!File.Exists(ConfigFilePath))
                {

                    string directory = ConfigFilePath.Substring(0, ConfigFilePath.LastIndexOf('\\'));
                    if (!Directory.Exists(directory))
                        Directory.CreateDirectory(ConfigFilePath);
                    if (!File.Exists(ConfigFilePath))
                        File.Create(ConfigFilePath);
                }
                return (IConfig)SerializationHelper.Load(ConfigInfoType, ConfigFilePath);
            }
        }
        /// <summary>
        /// 保存配置到文件中 
        /// </summary>
        /// <param name="configinfo"></param>
        /// <returns></returns>
        protected bool SaveConfig(IConfig configinfo)
        {
            return SerializationHelper.Save(configinfo, ConfigFilePath);
        }
    }
}
